package com.mobvel.zxstdzgl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.mobclick.android.MobclickAgent;
import com.mobvel.zxstdzgl.ui.MyDialog;
import com.mobvel.zxstdzgl.utils.AdTool;
import com.mobvel.zxstdzgl.utils.IndexHelper;
import com.mobvel.zxstdzgl.utils.PreferencesHelper;

public class ArticleActivity extends Activity implements OnTouchListener {

	private boolean mNightMode = false;

	private int mCateId;
	private String mArticleName;
	private int mIndex;
	private int mArtNum;

	private LayoutInflater inflater;
	private PreferencesHelper mHelper;

	private LinearLayout llParent;
	private ViewFlipper vfTouchArea;
	private TextView tvTitle1;
	private TextView tvContent1;
	private TextView tvTitle2;
	private TextView tvContent2;
	private ImageButton ibLast;
	private ImageButton ibNext;
	private CheckBox cbLight;

	private GestureDetector detector;
	
	private String mTitle1;
	private String mContent1;
	private String mTitle2;
	private String mContent2;
	
	private boolean mHasShowTip = false;
	
	private AdTool mAdTool;
	

	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.article_view);
		inflater = getLayoutInflater();
		mHelper = new PreferencesHelper(this);
		mHelper.put("NightMode", false);
		
		Intent i = getIntent();
		mCateId = i.getIntExtra("CateId", 0);
		mArtNum = i.getIntExtra("ArticleNum", 0);
		mArticleName = i.getStringExtra("ArticleName");
		mIndex = i.getIntExtra("ArticleIndex", 0);

		if (TextUtils.isEmpty(mArticleName) || mArtNum <= 0 || mCateId < 0
				|| mIndex <= 0) {
			finish();
		}

		llParent = (LinearLayout) findViewById(R.id.ll_parent);

		vfTouchArea = (ViewFlipper)findViewById(R.id.vf_toucharea);
		vfTouchArea.setOnTouchListener(this);
		detector = new GestureDetector(this, new PageGestureListener());
		tvTitle1 = (TextView) findViewById(R.id.tv_title1);
		tvContent1 = (TextView) findViewById(R.id.tv_content1);
		tvTitle2 = (TextView) findViewById(R.id.tv_title2);
		tvContent2 = (TextView) findViewById(R.id.tv_content2);
//		tvTitle3 = (TextView) findViewById(R.id.tv_title3);
//		tvContent3 = (TextView) findViewById(R.id.tv_content3);
		
		ibLast = (ImageButton) findViewById(R.id.ib_last);
		ibLast.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showPrevious();
			}
		});
		ibNext = (ImageButton) findViewById(R.id.ib_next);
		ibNext.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showNext();
			}
		});

		cbLight = (CheckBox) findViewById(R.id.cb_light);
		cbLight.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {

				if(isChecked) {
					mNightMode = true;
				}else {
					mNightMode = false;
				}
				setModeView();
			}
		});
		
		setModeView();
		refreshData(0);
		showTip();

		mAdTool = new AdTool(this);
	}
	
	private void showTip() {
		mHasShowTip = mHelper.getBoolean("HasShowedTip", false);
		if(mHasShowTip) {
			return;
		}else {
			final MyDialog dialog = new MyDialog(this);
			View layTip = inflater.inflate(R.layout.tip_layout, null);
			
			dialog.setView(layTip);
			layTip.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
			mHelper.put("HasShowedTip", true);
		}
    }
	
	private void setModeView() {
		if (mNightMode) {
			llParent.setBackgroundResource(R.drawable.night_bg);
			int ly = getResources().getColor(R.color.lgray);
			tvTitle1.setTextColor(ly);
			tvTitle2.setTextColor(ly);
			int lw = getResources().getColor(R.color.lyellow);
			tvContent1.setTextColor(lw);
			tvContent2.setTextColor(lw);
			ibLast.setImageResource(R.drawable.last_2);
			ibNext.setImageResource(R.drawable.next_2);
		} else {
			llParent.setBackgroundResource(R.drawable.day_bg);
			int blue = getResources().getColor(R.color.dred);
			tvTitle1.setTextColor(blue);
			tvTitle2.setTextColor(blue);
			int black = getResources().getColor(R.color.black);
			tvContent1.setTextColor(black);
			tvContent2.setTextColor(black);
			ibLast.setImageResource(R.drawable.last_1);
			ibNext.setImageResource(R.drawable.next_1);
		}
	}

	public void changeNightMode() {
		mNightMode = !mNightMode;
		cbLight.setChecked(mNightMode);
		mHelper.put("NightMode", mNightMode);
		setModeView();
	}

	private void showPrevious() {
		if (mIndex <= 1) {
			mAdTool.showOffers();
			Toast t = Toast.makeText(ArticleActivity.this,
					R.string.toast_is_first, Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER, 0, 0);
			t.show();
		} else {
			mIndex--;
			refreshData(1);
			vfTouchArea.showPrevious();
			mAdTool.dealAd();
		}
	}

	private void showNext() {
		if (mIndex >= mArtNum) {
			mAdTool.showOffers();
			Toast t = Toast.makeText(ArticleActivity.this,
					R.string.toast_is_last, Toast.LENGTH_SHORT);
			t.setGravity(Gravity.CENTER, 0, 0);
			t.show();
		} else {
			mIndex++;
			refreshData(2);
			vfTouchArea.showNext();
			mAdTool.dealAd();
		}
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return detector.onTouchEvent(event);
	}
	
	public void onResume() {
		super.onResume();
		
		MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause();
		
		MobclickAgent.onPause(this);
	}

	public void onDestroy() {

		super.onDestroy();
	}
	
	private String loadTitle(int index) {
		List<String> artList = IndexHelper.getAssetData(getResources(), mCateId);
		return artList.get(index-1);
	}
	
	private String loadContent(int index) {
		try {
			AssetManager localAssetManager = getResources().getAssets();
			String str = index + ".txt";
			InputStream input = localAssetManager.open(str);
			if (null == input) {
				Toast.makeText(this, R.string.tip_article_error,
						Toast.LENGTH_SHORT).show();
			}
			// 方法一：一次性读取
			int length = input.available();
			byte[] buffer = new byte[length];
			input.read(buffer);
			String mContent = new String(buffer);
			
			return ("\t" + mContent.trim() + "\n\n");
			
		} catch (IOException localIOException) {
			//
		}
		
		return null;
	}

	private void refreshData(int direction) {
		int viewId = vfTouchArea.getDisplayedChild();
		
		if(1 == direction || 2 == direction) {
			viewId = (viewId+1)%2;
		}
		
		switch(viewId) {
		case 0:
			mTitle1 = loadTitle(mIndex);
			mContent1 = loadContent(mIndex);
			tvTitle1.setText(mTitle1);
			tvContent1.setText(mContent1);
			break;
		case 1:
			mTitle2 = loadTitle(mIndex);
			mContent2 = loadContent(mIndex);
			tvTitle2.setText(mTitle2);
			tvContent2.setText(mContent2);
			break;
//		case 2:
//			mTitle3 = loadTitle(mIndex);
//			mContent3 = loadContent(mIndex);
//			tvTitle3.setText(mTitle3);
//			tvContent3.setText(mContent3);
//			break;
		}
		
	}
	
//	private boolean isSaved() {
//		int num = mHelper.getInt("RecordNum", 0);
//		for (int i = 1; i <= num; i++) {
//			if (mArticleName.equals(mHelper.getString("mArticleName" + i,
//					"empty"))) {
//				return true;
//			}
//		}
//
//		return false;
//	}

//	private void saveRecord() {
//		int num = mHelper.getInt("RecordNum", 0);
//		if (isSaved()) {
//			return;
//		}
//		num++;
//		mHelper.put("RecordNum", num);
//		mHelper.put("mArticleName" + num, mArticleName);
//		mHelper.put("SaveTime" + num, StringUtil.getTimeStr());
//	}
//
//	private void removeRecord() {
//		int num = mHelper.getInt("RecordNum", 0);
//		for (int i = 1; i <= num; i++) {
//			String record = mHelper.getString("mArticleName" + i, "empty");
//			if (record.equals(mArticleName)) {
//				mHelper.remove("mArticleName" + i);
//				mHelper.remove("mContent" + i);
//				mHelper.remove("SaveTime" + i);
//				break;
//			}
//		}
//	}

	protected void share() {
		String desc = mArticleName;
		Intent intent = new Intent("android.intent.action.SEND");
		intent.setType("text/plain");
		intent.putExtra("android.intent.extra.TEXT", desc);
		intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_title));
		Intent localIntent2 = Intent.createChooser(intent,
				getString(R.string.share_title));
		startActivity(localIntent2);
	}
	
	private class PageGestureListener extends SimpleOnGestureListener {
		/**
		 * 注意：OnGestureListener下面留个重载的方法，有实现则return true，没实现则return false
		 * 
		 * @param e
		 * @return
		 */
		public boolean onDoubleTap(MotionEvent e) {
			changeNightMode();
			return true;
		}

		@Override
		public boolean onDown(MotionEvent e) {
			// TODO Auto-generated method stub
			return true;

		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			// 用户按下屏幕，快速移动后松开（就是在屏幕上滑动）
			// e1:第一个ACTION_DOWN事件（手指按下的那一点）
			// e2:最后一个ACTION_MOVE事件 （手指松开的那一点）
			// velocityX:手指在x轴移动的速度 单位：像素/秒
			// velocityY:手指在y轴移动的速度 单位：像素/秒
			if (e1.getX() - e2.getX() > 60) {
				// 下一页
				vfTouchArea.setInAnimation(AnimationUtils.loadAnimation(ArticleActivity.this,
						R.anim.push_left_in));
				vfTouchArea.setOutAnimation(AnimationUtils.loadAnimation(ArticleActivity.this,
						R.anim.push_left_out));
				showNext();
				return true;
			} else if (e2.getX() - e1.getX() > 60) {
				// 上一页
				vfTouchArea.setInAnimation(AnimationUtils.loadAnimation(ArticleActivity.this,
						R.anim.push_right_in));
				vfTouchArea.setOutAnimation(AnimationUtils.loadAnimation(ArticleActivity.this,
						R.anim.push_right_out));
				showPrevious();
				return true;
			}

			return false;
		}

		@Override
		public void onLongPress(MotionEvent e) {
			// TODO Auto-generated method stub
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
				float distanceY) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void onShowPress(MotionEvent e) {
			// TODO Auto-generated method stub
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			// TODO Auto-generated method stub
			return false;
		}
	}
}
